package com.ho1ho.springboot.framework.core.annotations;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.beanutils.BeanUtils;

// https://stackoverflow.com/questions/1972933/cross-field-validation-with-hibernate-validator-jsr-303
// http://stackoverflow.com/questions/11890334/cross-field-validation-with-hibernatevalidator-displays-no-error-messages
// http://forum.spring.io/forum/spring-projects/web/81607-help-with-creating-custom-annotation-for-form-validation
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {
	private String firstFieldName;
	private String secondFieldName;
	private String errorMessageName;

	public void initialize(final FieldMatch constraintAnnotation) {
		firstFieldName = constraintAnnotation.first();
		secondFieldName = constraintAnnotation.second();
		errorMessageName = constraintAnnotation.message();
	}

	public boolean isValid(final Object value, final ConstraintValidatorContext context) {
		boolean isValid = false;
		try {
			final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
			final Object secondObj = BeanUtils.getProperty(value, secondFieldName);

			isValid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
		} catch (final Exception ignore) {
			// ignore
			ignore.printStackTrace();
		}
		// If the validation failed
		if (!isValid) {
			context.disableDefaultConstraintViolation();
			// In the initialize method you get the errorMessage:
			// constraintAnnotation.message();
			context.buildConstraintViolationWithTemplate(errorMessageName).addPropertyNode(firstFieldName)
					.addConstraintViolation();
		}
		return isValid;
	}
}